package com.github.luoshu.open.shiro;

import com.github.luoshu.open.shiro.redis.RedisManager;
import com.github.luoshu.open.shiro.redis.RedisSession;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.SessionFactory;

import java.util.UUID;

/**
 * 基于 redis 的 session.
 * 继承 SimpleSessionFactory ， 这个也是 DefaultWebSessionManager 中默认的 sessionFactory
 * @author inme
 */
public class SuperSessionFactory implements SessionFactory {

    /**
     * 会话的超时时间，单位：分钟。
     * 默认为 30分钟
     */
    private int sessionTimeMinute = 30;

    private RedisManager redisManager;

    public SuperSessionFactory(RedisManager redisManager) {
        this.redisManager = redisManager;
    }

    @Override
    public Session createSession(SessionContext initData) {
        RedisSession redisSession = new RedisSession(createSessionId() , redisManager, sessionTimeMinute);
        if (initData != null) {
            String host = initData.getHost();
            if (host != null) {
                redisSession.setHost(host);
            }
        }
        return redisSession;
    }

    /**
     * 设置会话的超时时间
     * @param sessionTimeMinute
     */
    public void setSessionTimeMinute(int sessionTimeMinute) {
        this.sessionTimeMinute = sessionTimeMinute;
    }

    public int getSessionTimeMinute() {
        return sessionTimeMinute;
    }

    public RedisManager getRedisManager() {
        return redisManager;
    }

    protected String createSessionId(){
        return UUID.randomUUID().toString();
    }
}
